<template>
  <view class="container">
    <uv-navbar 
      class="bold-title" 
      title="新增疫苗记录" 
      @leftClick="leftClick"
      :safeAreaInsetTop="true"
      :placeholder="true"
      :height="'44px'"
    ></uv-navbar>
    
    <view class="content-area">
      <InfoTitleList :infoTitleList="animalInfoList0"></InfoTitleList>
      <view class="form-item">
        <text class="label">牲畜Id</text>
        <input v-model="formData.F_liveid" placeholder="牲畜Id" class="input" />
      </view>  
      <view class="form-item">
        <text class="label">牧民</text>
        <input v-model="formData.F_Name" placeholder="韩梅梅" class="input" />
      </view>
      <view class="form-item">
        <text class="label">电话</text>
        <input v-model="formData.F_PHone" placeholder="未填写" class="input" />
      </view>
      <view class="form-item">
        <text class="label">接种地址</text>
        <input v-model="formData.F_Address" placeholder="未选择" class="input" />
      </view>

      <InfoTitleList :infoTitleList="animalInfoList"></InfoTitleList>
      <view class="form-item">
        <text class="label">疫苗名称</text>
        <input v-model="formData.F_Title" placeholder="口蹄疫疫苗" class="input" />
      </view>
      <view class="form-item">
        <text class="label">疫苗批次</text>
        <input v-model="formData.F_Batch" placeholder="未填写" class="input" />
      </view>
      <view class="form-item">
        <text class="label">接种支数</text>
        <input v-model.number="formData.F_Number" placeholder="1" type="number" class="input" />
      </view>

      <InfoTitleList :infoTitleList="animalInfoList1"></InfoTitleList>
      <view class="form-item">
        <text class="label">选择牲畜</text>
        <CattleDropdown 
                  :cattleList="cattleList" 
                  @select="handleCattleSelect" 
                  :placeholder="xzq[0].placeholder"
                />
      </view>
      <view class="form-item">
        <text class="label">备注</text>
        <input v-model="formData.F_Remark" placeholder="" class="input" />
      </view>
    </view>
    
    <view class="header">
      <button class="add-button" @click="handleSubmit">确定注射</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { addVaccine, getCattleList } from '@/api/manageRight.js';
import InfoTitleList from '@/components/Animals/InfoTitleList.vue';
import CattleDropdown from '@/components/Quarantinehome/CattleDropdown.vue'; // 引入自定义下拉框组件
//选择器名称
const xzq = [
  { 
    placeholder: '123456' // 新增字段存储 placeholder 值
  }
];
// 断行信息
const animalInfoList0 = [{ title: '牧民信息（操作员）' }];
const animalInfoList = [{ title: '疫苗信息' }];
const animalInfoList1 = [{ title: '添加牲畜' }];

// 表单数据
const formData = ref({
  F_liveid: '',
  F_Title: '',
  F_Address: '',
  F_Name: '',
  F_Batch: '',
  F_PHone: '',
  F_Number: ' ', 
  F_Remark: ''
});

// 牲畜列表
const cattleList = ref([]);

// 获取牲畜列表
const fetchCattleList = async () => {
  try {
    const response = await getCattleList();
    if (response.code === 200 && response.data) {
      cattleList.value = response.data.map(item => ({
        id: item.F_Id,
        imei: item.F_IMEI
      }));
    }
  } catch (error) {
    console.error('获取牲畜列表失败:', error);
    uni.showToast({
      title: '获取牲畜列表失败',
      icon: 'none',
      duration: 2000
    });
  }
};



// 提交表单事件
const handleSubmit = async () => {
  // 校验必填字段
  const requiredFields = [
    'F_liveid', // 牲畜ID
    'F_Title',  // 疫苗名称
    'F_Address', // 接种地址
    'F_Name',    // 牧民姓名
    'F_Number'   // 接种支数
  ];
  
  const missing = requiredFields.filter(field => {
    // 特殊处理数值类型
    if (field === 'F_Number') {
      return formData.value[field] === '' || isNaN(formData.value[field]) || formData.value[field] <= 0;
    }
    return !formData.value[field];
  });

  if (missing.length > 0) {
    uni.showToast({
      title: `缺少必填字段：${missing.join(', ')}`,
      icon: 'none',
      duration: 2000
    });
    return;
  }

  try {
    // 准备提交的数据
    const submitData = {
      ...formData.value,
      // 确保F_Number是数值类型
      F_Number: Number(formData.value.F_Number)
    };

    // 调用接口
    const response = await addVaccine(submitData);
    
    if (response.code === 200) {
      console.log(response.message);
      uni.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 2000
      });
      uni.navigateBack();
    } else {
      uni.showToast({
        title: response.message || '添加失败',
        icon: 'none',
        duration: 2000
      });
    }
  } catch (error) {
    console.error('接口调用失败:', error);
    
    // 显示更友好的错误信息
    let errorMessage = '网络请求失败，请重试';
    if (error.response && error.response.status === 500) {
      errorMessage = '服务器内部错误，请稍后再试';
    }
    
    uni.showToast({
      title: errorMessage,
      icon: 'none',
      duration: 3000
    });
  }
};

// 返回按钮事件
const leftClick = () => {
  uni.navigateBack();
};

// 页面加载时获取牲畜列表
onMounted(() => {
  fetchCattleList();
});
</script>

<style lang="scss" scoped>
// 样式部分保持不变
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.bold-title {
  font-weight: bold;
}

.content-area {
  flex: 1;
  overflow: auto;
  padding: 30rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.label {
  font-size: 14px;
  color: #333;
  margin-left: 4%;
  text-align: right;
  padding-right: 10px;
}

.input {
  font-size: 14px;
  color: #666;
  width: 70%;
  text-align: right;
  background-color: #fff;
  border-radius: 4px;
  padding: 10px;
  outline: none;
}

.select-button {
  font-size: 14px;
  color: #0bcb75;
  background-color: transparent;
  border: none;
  padding: 0;
}

.header {
  padding: 30rpx;
  background-color: white;
  z-index: 100;
}

.add-button {
  background-color: #0bcb75;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 16rpx;
  width: 100%;
  font-size: 32rpx;
  position: fixed;
  bottom: 0;
  left: 0;
}
</style>